package com.sf.sms.software.action;

import com.google.common.collect.Maps;
import com.sf.sms.software.entity.Software;
import com.sf.sms.software.entity.dto.SoftwareDTO;
import com.sf.sms.software.service.SoftwareService;
import com.sf.sms.user.entity.User;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 软件操作：控制类
 * Created by zhangbo 01084074 on 2016/8/25.
 */
@Controller
@RequestMapping(value = "/software")
public class SoftwareAction {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SoftwareService softwareService;

    /**
     * 获取软件
     *
     * @param pageNum
     * @return
     *
     * @author  zhangbo 01084074 on 2016/9/2.
     */
    @ResponseBody
    @RequestMapping(value = "/get")
    public Map<String, Object> getSoftware(Integer pageNum,Long categoryId) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<SoftwareDTO> softwareList = new ArrayList<SoftwareDTO>();
        Long total = 0l;
        if ( categoryId == null ) {
            softwareList = softwareService.getAllSoftware(pageNum);
            total = softwareService.getAllSoftwareCount();
        } else {
            softwareList = softwareService.getSoftwareByCategoryId(categoryId,pageNum);
            total = softwareService.getSoftwareCountByCategoryId(categoryId);
        }


        map.put("status", "success");
        map.put("items", softwareList);
        map.put("total", total);
        return map;
    }

    /**
     * 搜索软件
     *
     * @param pageNum   分页：页数
     * @param searchContent   搜索内容
     * @return
     *
     * @author  zhangbo 01084074 on 2016/9/5.
     */
    @ResponseBody
    @RequestMapping(value = "/search")
    public Map<String, Object> searchSoftware(Integer pageNum, String searchContent) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<SoftwareDTO> softwareList = new ArrayList<SoftwareDTO>();
        Long total = 0l;
        softwareList = softwareService.searchSoftware(searchContent, pageNum);
        total = softwareService.searchSoftwareCount(searchContent);

        map.put("status", "success");
        map.put("items", softwareList);
        map.put("total", total);
        return map;
    }

    @RequestMapping(value = "/getSoftware")
    public String getSoftwareById(@RequestParam(required = true) String id,
                                  Model model) {
        Map<String, Object> map = new HashMap<String, Object>();
        if(StringUtils.isNotEmpty(id)) {
            model.addAttribute("software",softwareService.getSoftwareById(Long.valueOf(id)));
            model.addAttribute("status","success");
        } else {
            model.addAttribute("software", null);
            model.addAttribute("status", "failed");
        }
        return "softwareDetail";
    }

    @RequestMapping("/add")
    public String createSoftware(HttpSession session, Model model,
                                              @ModelAttribute("software") Software software,
                                              @RequestParam(required = false) MultipartFile softIcon) {
        Map<String, Object> resultMaps = Maps.newHashMap();
        Subject subject = SecurityUtils.getSubject();
        subject.getSession();
        String iconPath = null;

        if(!softIcon.isEmpty()) iconPath = saveIcon(resultMaps, session, softIcon);
        if(StringUtils.isNotEmpty(iconPath)) {
            software.setIcon(iconPath);
        } else {
            software.setIcon("");
        }
        software.setStatus("0");
        software.setCreateTime(new Date());
        software.setCreator(getCurrentUser().getId().toString());
        software.setRemoteDownloadUrl(software.getDownloadUrl());
        software.setIsDelete("0");
        software.setIsFree("1");
        softwareService.createSoftware(software);

        return "redirect:/softwareUpload/upload";
    }

    private String saveIcon(Map<String, Object> maps, HttpSession session, MultipartFile softIcon) {
        String originalFilename = softIcon.getOriginalFilename();
        String filePath = session.getServletContext().getRealPath("/statics/public/");
        String prefix = UUID.randomUUID().toString();
        String fileName = prefix + originalFilename;
        File newFile = new File(filePath, fileName);

        try {
            InputStream is = softIcon.getInputStream();
            FileUtils.copyInputStreamToFile(is, newFile);
            maps.put("status", "success");
            return "/statics/public/" + fileName;
        } catch(IOException ex) {
            logger.error(ExceptionUtils.getRootCauseMessage(ex));
        }
        return null;
    }

    private User getCurrentUser() {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        return (User)session.getAttribute("currentUser");
    }
}
